<?php

// +----------------------------------------------------------------------
// | H1CMS © OpenSource CMS
// +----------------------------------------------------------------------
// | Copyright (c) 2014-2016 http://www.h1cms.com All rights reserved.
// | Copyright (c) 2014-2016 嘉兴领格信息技术有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Allen <allen@lg4.cn>
// +----------------------------------------------------------------------

namespace Lg\Storage;

use Lg\Database\Query;

/**
 * Description of KeyValue
 *
 * @author Allen <allen@lg4.cn>
 */
class KeyValue {

    public static function collection($name, $default = null) {
        $result = Query::table('key_value')
                ->select('name,value')
                ->where('collection', $name)
                ->fetchAll(\PDO::FETCH_KEY_PAIR);
        if (!empty($result)) {
            return $result;
        }
        return $default;
    }

    public static function get($collection, $name, $default = null) {
        $row = Query::table('key_value')
                ->select('name,value')
                ->where('collection', $collection)
                ->where('name', $name)
                ->fetchObject();
        if (!$row && empty($row->value)) {
            if ($row->serialized) {
                return unserialize($row->value);
            }
            return $row->value;
        }
        return $default;
    }

    public static function set($collection, $name, $value) {
        $row = Query::table('key_value')
                ->select('name,value')
                ->where('collection', $collection)
                ->where('name', $name)
                ->fetchObject();
        $serialized = is_object($value) || is_array($value) ? 1 : 0;
        if (!$row) {
            Query::table('key_value')->insert([
                'collection' => $collection,
                'name' => $name,
                'value' => $value,
                'serialized' => $serialized
            ]);
        } else {
            Query::table('key_value')
                    ->update(
                            [ 'value' => $value, 'serialized' => $serialized],
                            ['collection' => $collection, 'name' => $name]);
        }
        return $value;
    }

    public static function remove($collection, $name = null) {

        $conditions = ['collection' => $collection];
        if (!is_null($name)) {
            $conditions['name'] = $name;
        }
        Query::table('key_value')->delete($conditions);
    }

}
